package com.palm.vue.compiler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;

/**
 * vue 模板管理
 */
public class VueManager {
    static Map<String, byte[]> templates = new ConcurrentHashMap<>();
    static ICompiler compiler;
    static Object lock=new Object();
    /**
     * 4个模式,默认模式为4
     * 4:vue编译模版且压缩js
     * 3:vue编译模版不压缩js
     * 2:不编译模版压缩js
     * 1:不编译模版不压缩js
     */
    static int mode =4;

    //初始化
    public static void init(int _mode){
        mode =_mode;
        if(mode ==4|| mode ==3) {
            compiler = new VueCompiler(mode);
        }else if(mode ==2|| mode ==1){
            compiler=new VueCompressor(mode);
        }
//        try {
//            //建立文件索引,防止重复查找
//            VueManager.class.getClassLoader().getResources("/static");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
    public static byte[] get(String path) {
        if (templates.containsKey(path)) {
            return templates.get(path);
        }
        synchronized (lock){
            if (templates.containsKey(path)) {
                return templates.get(path);
            }
            InputStream stream = VueManager.class.getResourceAsStream("/static" + path);
            if (stream == null) {
                templates.put(path, null);
            } else {
                if(compiler==null){
                    return null;
                }
                String out = compiler.compile(stream);// VueCompressor.compile(stream);//compiler.compile(stream);
                byte[] outBytes=gzip(out);
                templates.put(path, outBytes);
                return outBytes;

            }
        }
        return null;
    }
    public static byte[] gzip(String text) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
                gzip.write(text.getBytes("UTF-8"));
            }
            return out.toByteArray();
        } catch (IOException e) {
            System.err.println("压缩失败:"+e);
        }
        return null;
    }
}
